package com.jinglu.cloud.security.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.jinglu.cloud.security.model.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName HttpPermissionManage
 * TODO
 * @Author zhaotengfei
 * @Date 2020/5/13
 * @Version V1.0
 **/
public class HttpPermissionManage implements PermissionManager {

    @Value("${permission.fegin.manager.url:localhost}")
    private String url;



    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Map<String, Collection<ConfigAttribute>> loadResourceDefine() {
//        logger.info("以http方式进行权限查询===============================");
//        HttpServletRequest request = getHttpServletRequest();
//        Map<String, String> headers = getHeaders(request);
//        String respon = HttpUtil.createGet(url.concat("/api/v2/member/permission/getPermissionAll")).addHeaders(headers).execute().body();
//        List<Permission> permissions = JSON.parseArray(respon, Permission.class);
        return new HashMap<>();
    }

    Map<String,Collection<ConfigAttribute>> convert(List<Permission> permissions){
        //logger.info("获取的权限集合==========" + JSON.toJSONString(permissions));
        Map<String, Collection<ConfigAttribute>> newData = new HashMap<>();
        if(CollectionUtil.isNotEmpty(permissions)){
            for (Permission permission : permissions) {
                List<ConfigAttribute> newValue = new ArrayList<>();
                newValue.add(new SecurityConfig(permission.getPermissionUrl()));
                newData.put(permission.getPermissionUrl(),newValue);
            }
        }
        return newData;
    }

    private HttpServletRequest getHttpServletRequest() {

        try {
            // 这种方式获取的HttpServletRequest是线程安全的
            return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        } catch (Exception e) {

            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {

        Map<String, String> map = new LinkedHashMap<>();

        Enumeration<String> enums = request.getHeaderNames();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }

        return map;
    }
}
